<template>
  <div class="member-list" v-loading="loading">
    <header class="header">
      <div class="filter">
        <!-- <el-cascader
          v-if="showSchoolFiler"
          placeholder="请选择学校"
          v-model="areaValue"
          :props="props"
          :show-all-levels="false"
          clearable
          filterable
        ></el-cascader> -->
        <el-select placeholder="角色" v-model="roleId" clearable>
          <el-option
            v-for="role in roleList"
            :key="role.F_role_id"
            :value="role.F_role_id"
            :label="role.F_role_name"
          >
          </el-option>
        </el-select>
        <el-select placeholder="年级" v-model="grade">
          <el-option
            v-for="item in gradeList"
            :key="item.id || ''"
            :value="item.name || ''"
            :label="item.name || ''"
          >
          </el-option>
        </el-select>
        <el-select placeholder="科目" v-model="subject">
          <el-option
            v-for="item in subjectList"
            :key="item.id || ''"
            :value="item.name || ''"
            :label="item.name || ''"
          >
          </el-option>
        </el-select>
        <el-input
          v-model="input"
          prefix-icon="el-icon-search"
          placeholder="输入姓名/手机号搜索"
          maxlength="15"
          @input="inputChange"
          clearable
        ></el-input>
      </div>

      <div class="header-right-panel">
        <div class="header-info-text">
          <i class="el-icon-info"></i>
          <span>该功能添加的是非参与阅卷及教学工作的老师信息</span>
        </div>

        <div class="tool-bar">
          <div class="item">
            <ButtonPermission code="member:add" mode="disable">
              <template #default="{ disabled }">
                <el-dropdown v-if="showImportBtn" :disabled="disabled" @command="handleCommand">
                  <span class="btn" :class="{ disabled: disabled }">新增成员<i class="el-icon-arrow-down"></i></span>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item command="add-user">单个新增</el-dropdown-item>
                      <ButtonPermission code="member:batchAdd" mode="disable">
                        <template #default="{ disabled: batchDisabled }">
                          <el-dropdown-item command="import-user" :disabled="batchDisabled">批量新增</el-dropdown-item>
                        </template>
                      </ButtonPermission>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
                <span v-else class="btn" :class="{ disabled: disabled }" @click="!disabled && addUser()">添加成员</span>
              </template>
            </ButtonPermission>
          </div>

          <div class="item">
            <ButtonPermission code="member:resetPwd" mode="disable">
              <template #default="{ disabled }">
                <span class="btn" :class="{ disabled: disabled }" @click="!disabled && (showResetPwd = true)">重置密码</span>
              </template>
            </ButtonPermission>
          </div>
        </div>
      </div>
    </header>
    <main class="main table-container">
      <div class="table-wrapper">
        <el-table ref="userTable" :data="userList" stripe border @data-updated="handleDataUpdated" class="responsive-table">
          <el-empty
            v-if="!loading && userList.length === 0"
            description="暂无数据"
            :image-size="100"
            ></el-empty>
          <el-table-column
            v-for="{ prop, label, width } in columnList"
            :key="prop"
            :label="label"
            :prop="prop"
            :min-width="width"
            align="center"
          >
            <template #default="scope">
              <template v-if="prop === 'F_roles'">
                <p v-for="{ F_role_name, F_id } in scope.row.F_roles" :key="F_id">
                  {{ F_role_name }}
                </p>
              </template>
              <template v-else-if="prop === 'teach_list'">
                <p v-for="{ F_name, F_subject } in scope.row.F_teach_list || []" :key="F_name + F_subject">
                  {{ getTeachStr(F_name, F_subject) }}
                </p>
              </template>

              <template v-else-if="prop === 'manage_list'">
                <p
                  v-for="{ F_name } in scope.row.F_manage_list || []"
                  :key="F_name"
                >
                  {{ F_name }}
                </p>
              </template>

              <template
                v-else-if="prop === 'grade_text' || prop === 'subject_text'"
              >
                <p
                  v-if="prop === 'grade_text'"
                  :title="scope.row.F_grades.map((e) => e.name).join('、')"
                >
                  {{ scope.row.grade_text }}
                </p>
                <p
                  v-else
                  :title="scope.row.F_subjects.map((e) => e.name).join('、')"
                >
                  {{ scope.row.subject_text }}
                </p>
              </template>

              <template v-else-if="prop === 'F_disable'">
                <div class="switch-wrapper">
                  <span class="switch-text">{{
                    scope.row.F_disable === 1 ? '禁用' : '启用'
                  }}</span>
                  <el-switch
                    v-model="scope.row.F_disable"
                    :active-value="0"
                    :inactive-value="1"
                    active-color="#009cff"
                    inactive-color="#e7e7e7"
                    @change="(val) => toSwitch(scope.$index, val)"
                    style="margin-left: 8px;"
                  />
                </div>
              </template>
              <template v-else-if="prop === 'operation'">
                <ButtonPermission code="member:edit" mode="disable">
                  <template #default="{ disabled }">
                    <span class="btn" :class="{ disabled: disabled }" @click="!disabled && editUser(scope.row)">编辑</span>
                  </template>
                </ButtonPermission>
                <ButtonPermission code="member:delete" mode="disable">
                  <template #default="{ disabled }">
                    <span class="btn" :class="{ disabled: disabled }" @click="!disabled && deleteUser(scope.$index, scope.row)">删除</span>
                  </template>
                </ButtonPermission>
              </template>
              <template v-else>
                <p>{{ scope.row[prop] }}</p>
              </template>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="table-footer">
        <el-pagination
          background
          layout="total, prev, pager, next"
          :total="userTotal"
          :page-size="pageSize"
          @current-change="changePage"
          v-model:current-page="page"
          :hide-on-single-page="false"
        >
        </el-pagination>
      </div>
    </main>
    <ResetPwd
      v-if="showResetPwd"
      :roleList="validRoleList"
      @close="showResetPwd = false"
      @update="getUsers"
    />
    <GenerateAccount
      v-if="showGenerateAccount"
      :roleList="validRoleList"
      @close="showGenerateAccount = false"
      @update="getUsers"
    />
    
    <!-- 新增/编辑成员对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="900px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      @close="handleDialogClose"
      @opened="handleDialogOpened"
    >
      <div class="dialog-content" v-loading="formLoading">
        <!-- 编辑模式下显示创建时间 -->
        <div class="dialog-header-info" v-if="isEditMode && formData.createTime">
          <span class="create-time">添加时间：{{ formData.createTime }}</span>
        </div>
        <div class="block">
          <div class="row">
            <div class="item role-name">
              <div class="label">
                <i>*</i>
                姓名
              </div>
              <div class="data">
                <el-input v-model="formData.F_user_name" maxlength="15"></el-input>
              </div>
            </div>
            <div class="item">
              <div class="label">
                <i>*</i>
                电话
              </div>
              <div class="data">
                <el-input v-model="formData.F_user_account" @input="handlePhoneInput"></el-input>
              </div>
            </div>
            <div class="item gender-item">
              <div class="label">
                <i>*</i>
                性别
              </div>
              <div class="data">
                <el-select v-model="formData.F_user_gender">
                  <el-option
                    v-for="item in genderList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  ></el-option>
                </el-select>
              </div>
            </div>
            <div class="item">
              <div class="label">所属单位</div>
              <div class="data">
                <el-input v-model="formData.F_employer" maxlength="15"></el-input>
              </div>
            </div>
            <div class="item role-item">
              <div class="label">
                <i>*</i>
                角色
              </div>
              <div class="data">
                <el-select
                  v-model="formData.checkedRoleList"
                  multiple
                  collapse-tags
                  placeholder="请选择角色"
                  value-key="F_role_id"
                >
                  <el-option
                    v-for="role in [...formRoleList, ...hideRoleList]"
                    :key="role.F_role_id"
                    :label="role.F_role_name"
                    :value="role"
                  ></el-option>
                </el-select>
              </div>
            </div>
            <div class="item" v-if="isEditMode">
              <div class="label">账号</div>
              <div class="data">
                <el-input v-model="formData.F_account" maxlength="20"></el-input>
              </div>
            </div>
            <div class="item reset-pwd" style="width: 300px" v-if="isEditMode">
              <div class="label">密码</div>
              <div class="data" style="display: flex">
                <el-input
                  v-model="password"
                  maxlength="18"
                  :disabled="pwdInputDisabled"
                  :type="pwdInputDisabled ? (isShowPwd ? 'text' : 'password') : 'text'"
                  :placeholder="pwdInputDisabled ? '点击眼睛图标查看密码' : '请输入新密码'"
                ></el-input>
                <div
                  class="reset-btn"
                  v-if="pwdInputDisabled"
                  @click="resetPassword"
                >
                  重置
                </div>
                <div v-else @click="editPwd" class="reset-btn confirm-edit">
                  保存
                </div>
                <i
                  class="el-icon-view"
                  @click="togglePwdShow"
                  v-if="pwdInputDisabled"
                ></i>
              </div>
            </div>
          </div>
        </div>
        <set-range 
          ref="setRange" 
          :type="isEditMode ? 1 : 0" 
          :checkedRoleList="formData.checkedRoleList"
        ></set-range>
        <!-- 编辑模式下显示教学信息 -->
        <div class="block" v-if="isEditMode && showTeachList">
          <div class="title">授课班级</div>
          <ul class="teach-list">
            <li v-for="{ F_name, F_subject } in teachInfo.F_teach_list" :key="F_name + F_subject">
              {{ `${F_name}-${subjectList.find((e) => e.id === F_subject)?.name}` }}
            </li>
          </ul>
        </div>
        <div class="block" v-if="isEditMode && showManageList">
          <div class="title">管理班级</div>
          <ul class="teach-list">
            <li v-for="{ F_name } in teachInfo.F_manage_list" :key="F_name">
              {{ F_name }}
            </li>
          </ul>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleDialogClose">取消</el-button>
          <el-button type="primary" @click="handleConfirm" :loading="formLoading">确认</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { debounce } from '@/utils/utils';
import { userListColumnList } from '@/utils/constant';
import { mapGetters } from 'vuex';
import api from '@/api/api';
import ResetPwd from './ResetPwd.vue';
import GenerateAccount from './GenerateAccount.vue';
import setRange from '@/components/rightsManage/setRange.vue';
import { subjectList } from '@/utils/maps';
import { ElMessageBox } from 'element-plus';

const INIT_SHOW_PWD = '******';
let hideRoleList = [];

// let schoolList = [];
const lazyLoad = async (node, resolve) => {
  let schoolList = []; // 改为局部变量
  const { level, value } = node;
  const areaId = level === 0 ? 0 : value;
  let list = [];
  switch (level) {
    case 0:
    case 1:
    case 2:
      const { F_districts } = await api.getUserDistrictList({
        F_parent_id: areaId,
      });
      list = F_districts.map(({ F_id, F_name }) => ({
        value: F_id,
        label: F_name,
        leaf: false,
      }));
      break;
    case 3:
      const { F_schools } = await api.getUserSchoolList({
        F_page: 0,
        F_area_id: areaId,
      });
      list = F_schools.map(({ F_id, F_name }) => ({
        value: F_id,
        label: F_name,
        leaf: true,
      }));
      schoolList = list;
    default:
      break;
  }
  resolve(list);
};

export default {
  name: 'MemberList',
  components: {
    ResetPwd,
    GenerateAccount,
    setRange,
  },
  data() {
    return {
      subjectMap: subjectList,
      areaValue: [],
      roleList: [],
      roleId: 'all', // 默认选中"全部角色"
      grade: '全部年级',
      subjectList: [],
      subject: '全部科目',
      input: '',
      page: 1,
      pageSize: 10,
      userList: [],
      userTotal: 0,
      loading: false,
      columnList: JSON.parse(JSON.stringify(userListColumnList)),
      props: {
        lazy: true,
        checkStrictly: true,
        lazyLoad,
      },
      showResetPwd: false,
      showGenerateAccount: false,
      isSchoolUser: false,
      debouncedSearch: null, // 防抖函数实例
      // 新增/编辑成员对话框
      dialogVisible: false,
      dialogTitle: '新增成员',
      isEditMode: false,
      formLoading: false,
      genderList: [],
      formRoleList: [], // 表单中使用的角色列表
      formData: {
        F_user_id: '',
        F_user_name: '',
        F_user_account: '',
        F_user_gender: 1,
        F_employer: '',
        F_account: '',
        checkedRoleList: [],
        createTime: ''
      },
      hideRoleList: [], // 编辑时不在当前角色列表中的角色
      password: INIT_SHOW_PWD,
      pwdInputDisabled: true,
      isShowPwd: false,
      teachInfo: {}, // 教学信息
    };
  },
  computed: {
    ...mapGetters('user', [
      'isSuperAdmin',
      'userPermission',
      'userGradeList',
      'userSchoolList',
    ]),
    ...mapGetters('school', [
      'currentSchool',
      'schoolName',
      'schoolId'
    ]),
    showSchoolFiler() {
      return this.isSuperAdmin || (this.userPermission?.level ?? 0) < 4;
    },
    showImportBtn() {
      return (
        !this.isSuperAdmin &&
        this.userPermission?.level === 4 &&
        this.userPermission?.school_list?.length === 1
      );
    },
    gradeList() {
      return [{ id: '', name: '全部年级' }].concat(this.userGradeList);
    },
    // 确保 roleList 始终是有效的数组
    validRoleList() {
      if (!this.roleList || !Array.isArray(this.roleList)) {
        return [];
      }
      return this.roleList.filter(role => {
        const roleId = role.F_role_id || role.id;
        return roleId !== undefined && roleId !== null;
      });
    },
    showTeachList() {
      const { F_teach_list } = this.teachInfo;
      return F_teach_list?.length;
    },
    showManageList() {
      const { F_manage_list } = this.teachInfo;
      return F_manage_list?.length;
    },
  },
  watch: {

    // 监听当前学校ID变化
    // '$store.state.school.currentSchoolId': {
    //   handler(newVal, oldVal) {
    //     console.log('监听到currentSchoolId变化:', newVal);
    //     if (newVal) {
    //       if (newVal !== oldVal) {
    //         this.loading = true; // 设置加载状态
    //         this.getNewData();
    //       } else if (this.loading && !this.treeData.length) {
    //         // 如果处于加载状态且没有树形数据，重新获取数据
    //         this.getNewData();
    //       }
    //     }
    //   },
    //   immediate: true
    // },
    roleId() {
      this.page = 1;
      this.getUsers();
    },
    grade() {
      this.page = 1;
      this.getUsers();
    },
    subject() {
      this.page = 1;
      this.getUsers();
    },
    areaValue(v) {
      this.page = 1;
      this.getUsers();
    },
  },
  async mounted() {
    // 打印当前学校信息
    console.log('当前学校信息:', {
      schoolId: this.schoolId,
      schoolName: this.schoolName,
      currentSchool: this.currentSchool
    });

    // 确保按钮权限数据已加载
    await this.ensureButtonPermissionsLoaded();

    // 初始化防抖函数
    this.debouncedSearch = debounce(() => {
      this.page = 1; // 搜索时重置到第一页
      this.getUsers();
    }, 500);

    await this.loadBaseData(); // 首次加载必须完成（getRoles 已同时更新 roleList 和 formRoleList）
    
    // 确保 roleId 默认选中"全部角色"（'all'）
    this.$nextTick(() => {
      if (this.roleId === null || this.roleId === undefined || this.roleId === '') {
        this.roleId = 'all';
      }
    });
    
    await this.getUsers();
    
    // 初始化性别列表
    this.genderList = this.$maps.genderList;
    // 注意：getFormRoles 不再需要单独调用，因为 getRoles 已经同时更新了 formRoleList
    // await this.getFormRoles();
  },
  activated() {
    // this.getRoles();
    // this.getSubjectList();
    // this.getUsers();
    // keep-alive缓存时直接刷新数据
      if (this.roleList.length === 0) {
        this.loadBaseData(); // 基础数据不存在时重新加载
      }
      this.getUsers(); // 总是刷新成员列表
  },
  beforeUnmount() {
    // 清理防抖函数
    if (this.debouncedSearch && this.debouncedSearch.cancel) {
      this.debouncedSearch.cancel();
    }
  },
  methods: {
    // 确保按钮权限数据已加载
    async ensureButtonPermissionsLoaded() {
      const menuTree = this.$store.state.user.menuTree || [];
      // 查找校务管理菜单
      const findMenu = (menus, targetName) => {
        for (const menu of menus) {
          const menuPath = menu.menu_path || '';
          if (menuPath) {
            const pathParts = menuPath.split('/').filter(part => part && part !== 'homepage');
            if (pathParts.length > 0 && pathParts[pathParts.length - 1] === targetName) {
              return menu;
            }
          }
          if (menu.children && Array.isArray(menu.children) && menu.children.length > 0) {
            const found = findMenu(menu.children, targetName);
            if (found) return found;
          }
        }
        return null;
      };
      
      const rightsManageMenu = findMenu(menuTree, 'rightsManage');
      if (rightsManageMenu && rightsManageMenu.id) {
        // 检查是否已有按钮数据（menu_type === 2）
        const hasButtons = rightsManageMenu.children && 
                          Array.isArray(rightsManageMenu.children) && 
                          rightsManageMenu.children.some(child => child.menu_type === 2);
        
        if (!hasButtons) {
          console.log('UserList: 按钮权限数据不存在，开始获取，菜单ID:', rightsManageMenu.id);
          try {
            // 登录时已经通过 fetchAllButtonPermissions 获取了完整的菜单树（包含所有子菜单和按钮）
            // 所以这里不需要再调用 fetchMenuChildren
            console.log('UserList: 按钮权限数据已在登录时加载完成');
          } catch (error) {
            console.error('UserList: 处理按钮权限数据失败:', error);
          }
        } else {
          console.log('UserList: 按钮权限数据已存在');
        }
      }
    },
    async loadBaseData() {
      await this.getRoles();
      await this.getSubjectList();
      this.getColumnList(); // 确保列数据初始化
    },

    getTeachStr(name, subject_id) {
      return `${name}-${
        this.subjectMap.find((e) => e.id === subject_id)?.name
      }`;
    },
    handleCommand(command) {
      switch (command) {
        case 'add-user':
          this.addUser();
          break;
        case 'import-user':
          ElMessageBox.confirm(
            '该功能添加的是非参与阅卷及教学工作的老师信息',
            '温馨提示',
            {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'info',
              center: true,
            }
          ).then(() => {
            this.toImport();
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消批量新增',
            });
          });
          break;
        default:
          break;
      }
    },

    toImport() {
      const schoolId = this.userPermission?.school_list?.[0]?.F_id;
      if (!schoolId) {
        this.$toast('无法获取学校信息');
        return;
      }
      this.$import(schoolId, this.$maps.importType.USER, () => {
        this.$toast('批量导入成员成功');
        this.page = 1;
        this.getUsers();
      });
    },
    changePage(val) {
      this.page = val;
      this.getUsers();
    },
    async toSwitch(index, newStatus) {
      // newStatus 是 switch 的新值 (0 或 1)
      // 0 表示启用，1 表示禁用
      const F_user_id = this.userList[index].F_user_id;
      const oldStatus = this.userList[index].F_disable;
      // 先更新 UI（v-model 已经自动更新了，但为了确保，我们显式设置）
      this.userList[index].F_disable = newStatus;
      const formData = new FormData();
      formData.append('F_user_id', F_user_id);
      formData.append('F_status', newStatus);
      try {
        const { F_responseMsg, F_responseNo } = await this.$api.disableUser(
          formData
        );
        if (F_responseNo !== 10000) {
          this.$toast(
            `${newStatus === 0 ? '启用' : '禁用'}失败:${F_responseMsg}`,
            1000
          );
          // 失败时恢复原值
          this.userList[index].F_disable = oldStatus;
        }
      } catch (err) {
        console.error(err);
        this.$toast(`${newStatus === 0 ? '启用' : '禁用'}失败`, 1000);
        // 失败时恢复原值
        this.userList[index].F_disable = oldStatus;
      }
    },

    async getRoles() {
      // 防止重复调用：如果已有数据，则不重复请求
      if (this.roleList.length > 1 && this.formRoleList.length > 0) {
        return;
      }
      
      try {
        // 使用新接口从rb_system_role表获取学校角色（F_is_school_role=1）
        const { F_role_list } = await this.$api.getSchoolRoles();
        if (F_role_list && Array.isArray(F_role_list)) {
          // 数据格式转换：将后端返回的字段名转换为前端使用的字段名
          const processedRoles = F_role_list
            .filter((e) => {
              // 过滤已删除的角色
              const isdel = e.isdel?.Int64 !== undefined ? e.isdel.Int64 : (e.F_isdel?.Int64 !== undefined ? e.F_isdel.Int64 : e.isdel || e.F_isdel || 0);
              return isdel === 0;
            })
            .map((role) => {
              // 统一字段名，确保兼容性
              const roleId = role.id || role.F_role_id || role.F_id;
              // 将 roleId 统一转换为字符串，确保类型一致（"全部角色"的 F_role_id 是空字符串）
              const roleIdStr = roleId !== undefined && roleId !== null ? String(roleId) : '';
              return {
                F_role_id: roleIdStr,
                F_role_name: role.role_name || role.F_role_name || '',
                F_role_code: role.role_code || role.F_role_code || '',
                F_role_type: role.role_type !== undefined ? role.role_type : (role.F_role_type?.Int64 !== undefined ? role.F_role_type.Int64 : role.F_role_type),
                F_disable: role.disable !== undefined ? role.disable : role.F_disable,
                F_isdel: role.isdel !== undefined ? role.isdel : role.F_isdel,
                F_describe: role.describe || role.F_describe,
                F_is_school_role: role.is_school_role !== undefined ? role.is_school_role : (role.F_is_school_role?.Int64 !== undefined ? role.F_is_school_role.Int64 : role.F_is_school_role),
              };
            });
          
          // 同时更新 roleList 和 formRoleList，避免重复请求
          // 使用 'all' 作为"全部角色"的值，而不是空字符串，因为 Element UI 可能无法正确显示空字符串
          this.roleList = [{ F_role_id: 'all', F_role_name: '全部角色' }, ...processedRoles];
          this.formRoleList = processedRoles;
          
          // 确保 roleId 默认选中"全部角色"（'all'）
          // 使用 $nextTick 确保 DOM 更新后再设置值
          this.$nextTick(() => {
            if (this.roleId === null || this.roleId === undefined || this.roleId === '' || this.roleId === 'all') {
              this.roleId = 'all';
            }
          });
        } else {
          this.roleList = [{ F_role_id: 'all', F_role_name: '全部角色' }];
          this.formRoleList = [];
        }
      } catch (error) {
        console.error('获取角色失败:', error);
        this.roleList = [{ F_role_id: 'all', F_role_name: '全部角色' }]; // 降级处理
        this.formRoleList = [];
      }
    },
    async getSubjectList() {
      // 防止重复调用：如果已有数据，则不重复请求
      if (this.subjectList.length > 1) {
        return;
      }
      
      let school_id =
        this.userSchoolList.length === 1 ? this.userSchoolList[0].F_id : '';
      const res = await this.$api.getSchoolSubject(school_id);
      // 安全地获取 subject_list，避免 userPermission 为 undefined 时报错
      const subject_list = this.userPermission?.subject_list;
      const list = subject_list?.length ? subject_list : res||[];
      list.unshift({ id: '', name: '全部科目' });
      this.subjectList = list;
    },
    async getUsers() {
      if (this.loading) return; // 防止重复请求
      this.loading = true;

      try {
        // 注意：不再在 getUsers 中调用 loadBaseData，避免重复请求
        // loadBaseData 已在 mounted 中调用，如果数据不存在说明页面初始化有问题
        // if (this.roleList.length === 0) {
        //   await this.loadBaseData();
        // }
        
        console.log('当前用户权限信息:', {
          isSuperAdmin: this.isSuperAdmin,
          userPermission: this.userPermission,
          areaValue: this.areaValue
        });
        
        const indexMap = {
          0: 'F_province_id',
          1: 'F_city_id',
          2: 'F_district_id',
          3: 'F_school_id',
        };
        const districtParams = {};
        this.areaValue.forEach((e, index) => {
          if (e) { // 只添加非空值
          districtParams[indexMap[index]] = e;
          }
        });
        
        // 如果 areaValue 中没有 F_school_id，但从 schoolId 计算属性中有值，则使用它
        // 注意：schoolId 可能是字符串，需要转换为数字
        if (!districtParams.F_school_id && this.schoolId) {
          const schoolIdNum = typeof this.schoolId === 'string' ? parseInt(this.schoolId, 10) : this.schoolId;
          if (!isNaN(schoolIdNum) && schoolIdNum > 0) {
            districtParams.F_school_id = schoolIdNum;
          }
        }
        
        console.log('API请求参数:', {
          F_name: this.input,
          F_role_id: this.roleId,
          F_school_name: this.schoolName,
          F_grade: this.grade === '全部年级' ? '' : this.grade,
          F_subject: this.subject === '全部科目' ? '' : this.subject,
          F_page: this.page,
          F_limit: this.pageSize,
          ...districtParams
        });

        this.loading = true;
        const { input, roleId, page, pageSize, grade, subject } = this;
        
        // 构建请求参数，同时传递 F_role_id 和 F_role_code
        const requestParams = {
            F_name: input,
            F_school_name: this.schoolName,
            F_grade: grade === '全部年级' ? '' : grade,
            F_subject: subject === '全部科目' ? '' : subject,
            F_page: page,
            F_limit: pageSize,
            ...districtParams,
        };
        
        // 如果选择了角色，同时传递 F_role_id 和 F_role_code
        // 'all' 表示"全部角色"，不需要传递角色参数
        if (roleId && roleId !== '' && roleId !== 'all') {
          requestParams.F_role_id = roleId;
          // 从 roleList 中查找对应的角色代码
          const selectedRole = this.roleList.find(role => {
            const id = role.F_role_id || role.id || role.F_id;
            return id === roleId || String(id) === String(roleId);
          });
          if (selectedRole && selectedRole.F_role_code) {
            requestParams.F_role_code = selectedRole.F_role_code;
          }
        }
        
        const { F_user_list, F_page_info, F_user_flag } =
          await this.$api.getUsers(requestParams);
        
        console.log('API返回数据:', { F_user_list, F_page_info, F_user_flag });
        
        this.isSchoolUser = F_user_flag === 1;
        const list = (F_user_list || []).filter((e) => e && e.F_isdel !== 1);
        
        console.log('过滤后的成员列表:', list);
        
        list.forEach((e) => {
          const { F_grades = [], F_subjects = [] } = e;
          
          console.log('处理用户数据:', { 
            user: e.F_user_name,
            grades: F_grades,
            subjects: F_subjects 
          });
          
          e.grade_text =
            F_grades.length === 0
              ? ''
              : F_grades.length === 1
              ? F_grades[0].name
              : `${F_grades[0].name}等${F_grades.length}个年级`;

          e.subject_text =
            F_subjects.length === 0
              ? ''
              : F_subjects.length === 1
              ? F_subjects[0].name
              : `${F_subjects[0].name}等${F_subjects.length}个学科`;
        });
        
        this.userList = list;
        this.userTotal = F_page_info?.F_total || 0;
        this.getColumnList();
        this.loading = false;
      } catch (error) {
        console.error('获取成员列表失败:', error);
        this.userList = [];
        this.userTotal = 0;
        this.loading = false;
      } finally {
        this.loading = false;
        this.$nextTick(() => {
          this.$refs.userTable?.doLayout(); // 手动触发布局计算
        });
      }
    },
    handleDataUpdated() {
      this.$refs.userTable?.doLayout();
    },
    getColumnList() {
      // const list = JSON.parse(JSON.stringify(userListColumnList));
      // if (!this.isSchoolUser) {
      //   list.splice(6, 2);
      // } else {
      //   list.splice(1, 0);
      // }
      // this.columnList = list;

      // 移除非必要条件判断
      this.columnList = JSON.parse(JSON.stringify(userListColumnList));
      if (this.isSchoolUser) {
        this.columnList.splice(6, 0); 
      } else {
        this.columnList.splice(1, 2);
      }
    },
    inputChange() {
      // 使用预定义的防抖函数
      if (this.debouncedSearch) {
        this.debouncedSearch();
      } else {
        // 如果防抖函数还未初始化，直接调用
        this.page = 1;
        this.getUsers();
      }
    },
    toRoleList() {
      this.$router.push({
        path: '/homepage/rightsManage/roleList',
      });
    },
    editUser(item) {
      this.isEditMode = true;
      this.dialogTitle = '编辑成员';
      
      // 清空 sessionStorage，使用组件内部数据
      sessionStorage.removeItem('edit_user_info');
      
      const {
        F_user_id,
        F_user_name,
        F_user_account,
        F_gender,
        F_employer,
        F_roles,
        F_create_datetime,
        F_account,
        F_passwd,
      } = item;
      
      this.formData.F_user_id = F_user_id;
      this.formData.F_user_name = F_user_name;
      this.formData.F_user_account = F_user_account;
      this.formData.F_user_gender = F_gender !== undefined && F_gender !== null ? F_gender : 1;
      this.formData.F_employer = F_employer || '';
      this.formData.F_account = F_account || '';
      this.formData.createTime = F_create_datetime || '';
      
      // 设置密码
      this.password = INIT_SHOW_PWD;
      this.pwdInputDisabled = true;
      this.isShowPwd = false;
      
      // 保存原始密码到 sessionStorage，供 togglePwdShow 使用
      if (F_passwd && F_passwd !== '') {
        const editUserInfo = { F_passwd };
        sessionStorage.setItem('edit_user_info', JSON.stringify(editUserInfo));
      }
      
      // 处理角色列表
      this.formData.checkedRoleList = [];
      this.hideRoleList = [];
      
      if (F_roles && Array.isArray(F_roles)) {
        F_roles.forEach((e) => {
          const roleId = String(e.F_id || e.F_role_id || '');
          const matchedRole = this.formRoleList.find((u) => {
            const uRoleId = String(u.F_role_id || '');
            return uRoleId === roleId || uRoleId === String(Number(roleId)) || String(Number(uRoleId)) === roleId;
          });
          if (matchedRole) {
            this.formData.checkedRoleList.push(matchedRole);
          } else {
            // 不在当前角色列表中的角色
            this.hideRoleList.push({
              F_role_id: e.F_id || e.F_role_id,
              F_role_name: e.F_role_name || e.RoleName,
              F_role_code: e.F_role_code || e.RoleCode,
            });
          }
        });
      }
      
      // 获取教学信息
      this.getTeachInfo();
      
      // 保存完整信息到 sessionStorage，供 setRange 组件使用
      sessionStorage.setItem('edit_user_info', JSON.stringify(item));
      
      this.dialogVisible = true;
      
      // 确保 setRange 组件数据加载
      this.$nextTick(() => {
        if (this.$refs.setRange) {
          this.$refs.setRange.getNewDistrict();
        }
      });
    },
    addUser() {
      ElMessageBox.confirm(
        '该功能添加的是非参与阅卷及教学工作的老师信息',
        '温馨提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'info',
          center: true,
        }
      )
        .then(() => {
          this.isEditMode = false;
          this.dialogTitle = '新增成员';
          this.resetFormData();
          // 清除 sessionStorage 中的编辑信息，确保新增模式
          sessionStorage.removeItem('edit_user_info');
          this.dialogVisible = true;
          // 确保 setRange 组件数据加载
          this.$nextTick(async () => {
            if (this.$refs.setRange) {
              // 如果有 schoolId，根据 schoolId 初始化区县和学校信息
              if (this.schoolId) {
                await this.$refs.setRange.initDistrictBySchoolId(this.schoolId);
              } else {
                // 否则使用默认方式初始化
                this.$refs.setRange.getNewDistrict();
              }
            }
          });
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消',
          });
        });
    },
    
    // 获取表单使用的角色列表（学校角色）
    async getFormRoles() {
      try {
        // 使用新接口从rb_system_role表获取学校角色（F_is_school_role=1）
        const { F_role_list } = await this.$api.getSchoolRoles();
        if (F_role_list && Array.isArray(F_role_list)) {
          this.formRoleList = F_role_list
            .filter((e) => {
              const isdel = e.isdel?.Int64 !== undefined ? e.isdel.Int64 : (e.F_isdel?.Int64 !== undefined ? e.F_isdel.Int64 : e.isdel || e.F_isdel || 0);
              return isdel === 0;
            })
            .map((role) => {
              return {
                F_role_id: role.id || role.F_role_id,
                F_role_name: role.role_name || role.F_role_name,
                F_role_code: role.role_code || role.F_role_code,
                F_role_type: role.role_type !== undefined ? role.role_type : (role.F_role_type?.Int64 !== undefined ? role.F_role_type.Int64 : role.F_role_type),
                F_disable: role.disable !== undefined ? role.disable : role.F_disable,
                F_isdel: role.isdel !== undefined ? role.isdel : role.F_isdel,
                F_describe: role.describe || role.F_describe,
                F_is_school_role: role.is_school_role !== undefined ? role.is_school_role : (role.F_is_school_role?.Int64 !== undefined ? role.F_is_school_role.Int64 : role.F_is_school_role),
              };
            });
        } else {
          this.formRoleList = [];
        }
      } catch (error) {
        console.error('获取角色失败:', error);
        this.formRoleList = [];
      }
    },
    
    // 重置表单数据
    resetFormData() {
      this.formData = {
        F_user_id: '',
        F_user_name: '',
        F_user_account: '',
        F_user_gender: 1,
        F_employer: '',
        F_account: '',
        checkedRoleList: [],
        createTime: ''
      };
      this.password = INIT_SHOW_PWD;
      this.pwdInputDisabled = true;
      this.isShowPwd = false;
      this.hideRoleList = [];
      this.teachInfo = {};
      this.isEditMode = false;
      sessionStorage.removeItem('edit_user_info');
    },
    
    // 关闭对话框
    handleDialogClose() {
      this.dialogVisible = false;
      setTimeout(() => {
        this.resetFormData();
      }, 300);
    },
    
    // 处理弹窗打开后
    handleDialogOpened() {
      if (!this.isEditMode) {
        // 新增模式，检查是否有预填充数据（从教师页面跳转过来的情况）
        this.$nextTick(async () => {
          const info = sessionStorage.getItem('edit_user_info');
          if (info) {
            try {
              const { F_gender, F_user_name, F_user_account } = JSON.parse(info);
              if (F_gender !== undefined) this.formData.F_user_gender = F_gender;
              if (F_user_name) this.formData.F_user_name = F_user_name;
              if (F_user_account) this.formData.F_user_account = F_user_account;
            } catch (e) {
              console.error('解析预填充数据失败:', e);
            }
          }
          
          // 新增模式，需要初始化数据范围组件
          if (this.$refs.setRange) {
            // 如果有 schoolId，根据 schoolId 初始化区县和学校信息
            if (this.schoolId) {
              await this.$refs.setRange.initDistrictBySchoolId(this.schoolId);
            } else {
              // 否则使用默认方式初始化
              this.$refs.setRange.getNewDistrict();
              this.$refs.setRange.getAccountDistrict();
            }
          }
        });
      } else {
        // 编辑模式，确保 setRange 数据已加载
        this.$nextTick(() => {
          if (this.$refs.setRange) {
            this.$refs.setRange.getNewDistrict();
          }
        });
      }
    },
    
    // 处理手机号输入
    handlePhoneInput(v) {
      this.formData.F_user_account = v.replace(/[\u200B-\u200D\uFEFF]/g, '').trim();
      if (this.formData.F_user_account.length > 11) {
        this.formData.F_user_account = this.formData.F_user_account.slice(0, 11);
      }
    },
    
    // 切换密码显示/隐藏
    togglePwdShow() {
      const userInfo = JSON.parse(sessionStorage.getItem('edit_user_info') || '{}');
      const { F_passwd } = userInfo;
      this.password = this.isShowPwd ? INIT_SHOW_PWD : F_passwd;
      this.isShowPwd = !this.isShowPwd;
    },
    
    // 重置密码
    resetPassword() {
      this.password = '123456';
      this.pwdInputDisabled = false;
    },
    
    // 修改密码
    async editPwd() {
      try {
        const params = {
          F_update_user_id: this.formData.F_user_id,
          F_phone: this.formData.F_user_account,
          F_password: this.password,
        };
        const formData = new FormData();
        for (const [k, v] of Object.entries(params)) {
          formData.append(k, v);
        }
        const { F_responseNo, F_responseMsg } = await this.$api.editUserPW(formData);
        if (F_responseNo !== 10000) {
          this.$toast('修改密码失败:', F_responseMsg);
        } else {
          this.$toast('修改密码成功');
          // 更新 sessionStorage 中的密码
          const editUserInfo = JSON.parse(sessionStorage.getItem('edit_user_info') || '{}');
          editUserInfo.F_passwd = this.password;
          sessionStorage.setItem('edit_user_info', JSON.stringify(editUserInfo));
          // 恢复显示状态
          this.password = INIT_SHOW_PWD;
          this.pwdInputDisabled = true;
          this.isShowPwd = false;
        }
      } catch (e) {
        console.error(e);
        this.$toast('修改密码失败，请联系后台成员');
      }
    },
    
    // 获取教学信息
    async getTeachInfo() {
      if (!this.isEditMode || !this.formData.F_user_name || !this.formData.F_user_account) {
        this.teachInfo = {};
        return;
      }
      try {
        this.teachInfo = await this.$api.getTeachInfo({
          F_name: this.formData.F_user_name,
          F_phone: this.formData.F_user_account,
        });
      } catch (error) {
        console.error('获取教学信息失败:', error);
        this.teachInfo = {};
      }
    },
    
    // 表单验证
    checkFormData() {
      if (!this.formData.F_user_name || this.formData.F_user_name.trim().length === 0) {
        this.$toast('请输入姓名');
        return false;
      }
      if (!this.formData.F_user_account || this.formData.F_user_account.length === 0) {
        this.$toast('请输入电话号码');
        return false;
      }
      if (this.formData.F_user_account.length !== 11) {
        this.$toast('请输入正确的电话号码');
        return false;
      }
      if (!this.formData.checkedRoleList || this.formData.checkedRoleList.length === 0) {
        this.$toast('请至少选择一个角色');
        return false;
      }
      
      const { newDistrict, accountDistrict } = this.$refs.setRange || {};
      if (!newDistrict || !accountDistrict) {
        this.$toast('数据范围组件未初始化');
        return false;
      }
      
      const { city_list, county_list, school_list, grade_list, subject_list } = newDistrict;

      if (
        this.formData.checkedRoleList.find((role) =>
          ['备课组长', '科组长'].includes(role.F_role_name)
        ) &&
        !subject_list.length
      ) {
        this.$toast('备课组长或科组长角色必须指定科目');
        return false;
      }

      if (
        this.formData.checkedRoleList.find((role) =>
          ['年级主任'].includes(role.F_role_name)
        ) &&
        !grade_list.length
      ) {
        this.$toast('"年级主任"角色必须指定年级');
        return false;
      }

      if (
        this.formData.checkedRoleList.find((role) =>
          ['教研员'].includes(role.F_role_name)
        ) &&
        !subject_list.length
      ) {
        this.$toast('"教研员"角色必须指定科目');
        return false;
      }

      if (city_list.length) newDistrict.level = 2;
      if (county_list.length) newDistrict.level = 3;
      if (school_list.length) newDistrict.level = 4;
      const currentLevel = newDistrict.level;
      if (currentLevel < accountDistrict.level) {
        const levelNameList = [
          '城市',
          '区（县）',
          '学校',
          '年级',
          '班级',
          '科目',
        ];
        const levelName = levelNameList[currentLevel];
        this.$toast(`请至少选择一个${levelName}`);
        return false;
      }
      return true;
    },
    
    // 确认提交
    async handleConfirm() {
      if (!this.checkFormData()) {
        return;
      }

      this.formLoading = true;
      try {
        const isUpdate = this.isEditMode;
        
        // 收集角色代码（学校用户，F_is_school_role=1）
        const roleCodeList = [
          ...this.formData.checkedRoleList.map((e) => e.F_role_code || String(e.F_role_id)),
          ...this.hideRoleList.map((e) => e.F_role_code || String(e.F_role_id)),
        ];
        
        // 获取区域信息
        const { newDistrict } = this.$refs.setRange;
        let districtInfo = '';
        if (newDistrict && Object.keys(newDistrict).length > 0) {
          const district = {
            province_list: newDistrict.province_list || [],
            city_list: newDistrict.city_list || [],
            county_list: newDistrict.county_list || [],
            level: newDistrict.level !== undefined ? newDistrict.level : 0,
            subject_list: newDistrict.subject_list || [],
            stage: newDistrict.stage !== undefined ? newDistrict.stage : null,
            school_list: newDistrict.school_list || [],
            grade_list: newDistrict.grade_list || [],
            class_list: newDistrict.class_list || [], // 添加班级列表
          };
          districtInfo = JSON.stringify(district);
        } else {
          districtInfo = JSON.stringify({
            province_list: [],
            city_list: [],
            county_list: [],
            level: 0,
            subject_list: [],
            stage: null,
            school_list: [],
            grade_list: [],
            class_list: [], // 添加班级列表
          });
        }
        
        // 获取当前选定的学校ID
        // 优先使用 schoolId 计算属性，如果没有则使用 '0'
        let schoolIdValue = '0';
        if (this.schoolId) {
          // schoolId 可能是数字或字符串，统一转换为字符串
          schoolIdValue = String(this.schoolId);
        }
        
        // 构建请求参数
        const params = {
          F_user_id: isUpdate ? this.formData.F_user_id : '',
          F_user_name: this.formData.F_user_name,
          F_user_account: this.formData.F_user_account,
          F_user_gender: this.formData.F_user_gender,
          F_employer: this.formData.F_employer || '',
          F_role_ids: JSON.stringify(roleCodeList),
          F_account: this.formData.F_account || '',
          F_passwd: isUpdate && this.password !== INIT_SHOW_PWD ? this.password : '',
          F_is_school_user: 1, // 学校用户
          F_district: districtInfo,
          F_school_id: schoolIdValue,
        };
        
        const { F_responseNo, F_responseMsg } = await this.$api.createOrUpdateUser(
          params,
          isUpdate
        );
        
        if (F_responseNo === 10000) {
          this.$toast(`${this.dialogTitle}成功`);
          this.dialogVisible = false;
          this.resetFormData();
          this.getUsers();
        } else {
          this.$toast(`${this.dialogTitle}失败。${F_responseMsg}`, true);
        }
      } catch (e) {
        console.error(e);
        this.$toast(`${this.dialogTitle}失败`);
      } finally {
        this.formLoading = false;
      }
    },
    deleteUser(index, item) {
      const { F_user_id, F_user_name } = item;
      this.$delete(F_user_name, async () => {
        try {
          const { F_responseNo, F_responseMsg } = await this.$api.deleteUserNew({
            F_user_id,
            F_user_type: 8,
          });
          if (F_responseNo === 10000) {
            this.$toast('删除该成员成功', 1200);
            if (
              // 删除的是当前页第一项
              index === 0 &&
              this.userTotal % this.pageSize === 1 &&
              this.userTotal !== 1 &&
              // 当前页是最后一页
              this.page === Math.ceil(this.userTotal / this.pageSize)
            )
              this.page = this.page - 1;
            console.log(this.page);
            this.getUsers();
          } else this.$toast(`删除该成员失败: ${F_responseMsg}`);
        } catch (e) {
          console.error(e);
          this.$toast('删除该成员失败');
        }
      });
    },
    exportData() {
      console.log('export data');
      this.$toast('功能改进中，尚未开放');
    },
  },
};
</script>

<style lang="less" scoped>
.member-list {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: #f5f7fa;
  padding: 16px;
  
  .header {
    min-height: 60px;
    padding: 12px 20px;
    background-color: #fff;
    border-radius: 4px;
    margin-bottom: 16px;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    align-items: center;
    gap: 12px;

    .header-right-panel {
      display: flex;
      align-items: center;
    }

    .header-info-text {
      display: flex;
      align-items: center;
      color: #e6a23c;
      font-size: 13px;
      padding: 6px 12px;
      background-color: #fdf6ec;
      border-radius: 4px;
      border: 1px solid #faecd8;
      white-space: nowrap;
      margin-right: 16px;

      i {
        margin-right: 6px;
        font-size: 14px;
      }
    }

    .filter {
      display: flex;
      align-items: center;
      gap: 10px;
      flex-wrap: wrap;
      
      .el-cascader {
        width: 150px;
      }
      .el-select {
        width: 120px;
        height: 32px;
        
        :deep(.el-input__inner) {
          height: 32px;
          line-height: 32px;
          border-radius: 4px;
          border-color: #dcdfe6;
          transition: all 0.3s;
          font-size: 13px;
          
          &:focus {
            border-color: #409eff;
          }
        }
      }
      .el-input {
        width: 200px;
        
      :deep(.el-input__inner) {
          height: 32px;
          line-height: 32px;
          border-radius: 4px;
          border-color: #dcdfe6;
          transition: all 0.3s;
          font-size: 13px;
          
          &:focus {
            border-color: #409eff;
            box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.1);
          }
      }
      :deep(.el-input__icon) {
          line-height: 32px;
        }
      }
    }
    .tool-bar {
      display: flex;
      align-items: center;
      gap: 0;
      
      .item {
        display: flex;
        align-items: center;
        position: relative;
        
        .btn {
          color: #409eff;
          cursor: pointer;
          font-size: 14px;
          padding: 6px 12px;
          border-radius: 4px;
          transition: all 0.3s;
          white-space: nowrap;
          
          &:hover:not(.disabled) {
            color: #66b1ff;
            background-color: #ecf5ff;
          }
          
          &.disabled {
            color: #c0c4cc;
            cursor: not-allowed;
            opacity: 0.6;
            background-color: transparent;
            
            &:hover {
              color: #c0c4cc;
              background-color: transparent;
          }
        }
        }
        
        :deep(.el-dropdown) {
          .btn {
            font-size: 14px;
          }
        }
        
        &:not(:last-child)::after {
          content: '';
          display: block;
          height: 12px;
          width: 1px;
          margin: 0 12px;
          background-color: #dcdfe6;
        }
      }
    }
  }

  .main {
    flex: 1;
    overflow: hidden;
    display: flex;
    flex-direction: column;
    background-color: #fff;
    border-radius: 4px;
    padding: 16px;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
    
    .table-wrapper {
      flex: 1;
      overflow: auto;
          
          &::-webkit-scrollbar {
        width: 6px;
        height: 6px;
          }
          
          &::-webkit-scrollbar-thumb {
        background-color: #c0c4cc;
        border-radius: 3px;
            
            &:hover {
          background-color: #a0a4ac;
            }
          }
          
          &::-webkit-scrollbar-track {
        background-color: #f5f7fa;
        border-radius: 3px;
      }
      
      :deep(.el-table) {
        border-radius: 4px;
        overflow: hidden;
        border: 1px solid #e4e7ed;
        
        .el-table__header {
          th {
            background-color: #fafafa;
            color: #606266;
            font-weight: 500;
            font-size: 13px;
            border-bottom: 1px solid #e4e7ed;
            padding: 10px 0;
            
            .cell {
              font-weight: 500;
        }
      }
    }

        .el-table__body {
          tr {
            transition: background-color 0.3s;
            
            &:hover {
              background-color: #f5f7fa;
            }
            
            td {
              padding: 10px 0;
              border-bottom: 1px solid #f0f0f0;
              
              .cell {
                font-size: 13px;
                color: #606266;
                
                p {
                  margin: 2px 0;
                  line-height: 1.4;
                }
              }
            }
          }
        }
      }
    }
    
    .switch-wrapper {
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 8px;
    
      .switch-text {
        display: inline-block;
        font-size: 14px;
        color: #606266;
        min-width: 32px;
      }
    }
    
    .btn {
      color: #409eff;
      cursor: pointer;
      font-size: 14px;
      padding: 4px 8px;
      border-radius: 4px;
      transition: all 0.3s;
      margin: 0 4px;
      
      &:hover:not(.disabled) {
        color: #66b1ff;
        background-color: #ecf5ff;
      }
      
      &.disabled {
        color: #c0c4cc;
        cursor: not-allowed;
        opacity: 0.6;
        
        &:hover {
          color: #c0c4cc;
          background-color: transparent;
        }
      }
    }
  }

  .table-footer {
    margin-top: 16px;
    display: flex;
    justify-content: flex-end;
    padding-top: 16px;
    border-top: 1px solid #e4e7ed;
    
    :deep(.el-pagination) {
      .el-pagination__total {
        font-size: 14px;
        color: #606266;
        margin-right: 16px;
      }
      
      .btn-prev,
      .btn-next {
        border-radius: 4px;
        transition: all 0.3s;
        
        &:hover {
          color: #409eff;
        }
      }
      
      .el-pager {
        li {
          border-radius: 4px;
          transition: all 0.3s;
          
          &.active {
            background-color: #409eff;
            color: #fff;
          }
          
          &:hover {
            color: #409eff;
          }
        }
      }
    }
  }
}

// 对话框样式
.dialog-content {
  padding: 20px 0;
  
  .dialog-header-info {
    margin-bottom: 20px;
    padding-bottom: 15px;
    border-bottom: 1px solid #e4e7ed;
    
    .create-time {
      font-size: 14px;
      color: #909399;
    }
  }
  
  .block {
    margin-bottom: 20px;
    
    .title {
      font-size: 16px;
      font-weight: bold;
      margin-bottom: 20px;
      color: #303133;
      padding-left: 4px;
      border-left: 3px solid #409eff;
    }
    
    .row {
      display: flex;
      flex-wrap: wrap;
      gap: 20px;
      
      .item {
        flex: 0 0 calc(33.333% - 14px);
        min-width: 200px;
        
        &.role-name {
          flex: 0 0 calc(25% - 15px);
        }
        
        &.gender-item {
          flex: 0 0 calc(25% - 15px);
        }
        
        &.role-item {
          flex: 0 0 calc(50% - 10px);
        }
        
        .label {
          margin-bottom: 8px;
          color: #606266;
          font-size: 14px;
          font-weight: 500;
          display: flex;
    align-items: center;
          
          i {
            color: #f56c6c;
            margin-right: 4px;
            font-style: normal;
          }
        }
        
        .data {
          .el-input,
          .el-select {
            width: 100%;
            
            :deep(.el-input__inner) {
              border-radius: 4px;
              transition: all 0.3s;
              
              &:focus {
                border-color: #409eff;
                box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.1);
              }
            }
          }
          
          :deep(.el-select) {
            .el-input__inner {
              &:focus {
                border-color: #409eff;
              }
            }
          }
        }
        
        &.reset-pwd {
          .data {
            display: flex;
            align-items: center;
            
            .el-input {
              flex: 1;
            }
            
            .reset-btn {
              font-size: 14px;
              width: 70px;
              height: 40px;
              line-height: 40px;
              text-align: center;
              color: #009cff;
              background-color: #f1efef;
              border-radius: 0 4px 4px 0;
              cursor: pointer;
    flex-shrink: 0;
            }
            
            .confirm-edit {
              color: #009cff;
    background-color: #fff;
              border: 1px solid #ccc;
            }
            
            i {
              width: 20px;
              height: 20px;
              cursor: pointer;
              color: #909399;
              font-size: 16px;
              margin-left: 8px;
              transition: color 0.3s;
              flex-shrink: 0;
              
              &:hover {
                color: #409eff;
              }
            }
          }
        }
      }
    }
    
    .teach-list {
    display: flex;
      flex-wrap: wrap;
      list-style: none;
      padding: 0;
      margin: 0;
      
      li {
      display: inline-block;
        padding: 10px 16px;
        margin: 0 10px 10px 0;
        border: 1px solid #d9d9d9;
        border-radius: 4px;
        background-color: #f5f7fa;
      }
    }
  }
}

:deep(.el-dialog) {
  border-radius: 8px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  
  .el-dialog__header {
    padding: 20px 24px 16px;
    border-bottom: 1px solid #e4e7ed;
    background-color: #fafafa;
    border-radius: 8px 8px 0 0;
    
    .el-dialog__title {
      font-size: 18px;
      font-weight: 600;
      color: #303133;
      line-height: 1.5;
    }
    
    .el-dialog__headerbtn {
      top: 20px;
      right: 24px;
      
      .el-dialog__close {
        font-size: 18px;
        color: #909399;
        transition: color 0.3s;
        
        &:hover {
          color: #303133;
        }
      }
    }
  }
  
  .el-dialog__body {
    padding: 24px;
    max-height: 70vh;
    overflow-y: auto;
    
    &::-webkit-scrollbar {
      width: 6px;
      height: 6px;
    }
    
    &::-webkit-scrollbar-thumb {
      background-color: #c0c4cc;
      border-radius: 3px;
      
      &:hover {
        background-color: #a0a4ac;
      }
    }
    
    &::-webkit-scrollbar-track {
      background-color: #f5f7fa;
      border-radius: 3px;
    }
  }
  
  .el-dialog__footer {
    padding: 16px 24px;
    border-top: 1px solid #e4e7ed;
    background-color: #fafafa;
    border-radius: 0 0 8px 8px;
    
    .dialog-footer {
      display: flex;
      justify-content: flex-end;
      gap: 12px;
      
      .el-button {
        min-width: 80px;
        padding: 10px 20px;
        border-radius: 4px;
        font-size: 14px;
        transition: all 0.3s;
        
        &.el-button--default {
          border-color: #dcdfe6;
          color: #606266;
          
          &:hover {
            border-color: #c0c4cc;
            color: #606266;
            background-color: #ecf5ff;
          }
        }
        
        &.el-button--primary {
          background-color: #409eff;
          border-color: #409eff;
          
          &:hover {
            background-color: #66b1ff;
            border-color: #66b1ff;
          }
          
          &:active {
            background-color: #3a8ee6;
            border-color: #3a8ee6;
          }
          
          &.is-loading {
            background-color: #409eff;
            border-color: #409eff;
          }
        }
      }
    }
  }
}
</style>
